<?php

namespace app\controller\system;

use app\model\system\SysDept;
use app\controller\BaseController;
use support\Request;
use support\Response;

class DeptController extends BaseController
{

    public function create(Request $request): Response
    {
        $data = $request->post();
        $dept = SysDept::create($data);
        if (!$dept) {
            return $this->error('创建失败');
        } else {
            return $this->success([]);
        }
    }

    public function form(int $id): Response
    {
        $dept = SysDept::find($id);
        if (!$dept) {
            return $this->error('用户不存在');
        }
        return $this->success($dept->getFormArray());
    }


    public function update(Request $request, int $id): Response
    {
        $data = $request->post();
        $dept = SysDept::find($id);

        if (!$dept) {
            return $this->error('用户不存在');
        }

        if ($dept->update($data)) {
            return $this->success($dept->getFormArray());
        } else {
            return $this->error('更新失败');
        }
    }

    public function delete(int $id): Response
    {
        $dept = SysDept::find($id);
        if (!$dept) {
            return $this->error('用户不存在');
        }
        if (!$dept->delete()) {
            return $this->error('删除失败');
        } else {
            return $this->success($dept->toArray());
        }
    }

    public function getTree(Request $request): Response
    {
        $keywords = $request->get("keywords");
        $status = $request->get("status");
        $depts = SysDept::deptTree(0, $status, $keywords);
        return $this->success($depts);
    }

    public function options(): Response
    {
        return $this->success(SysDept::optionTree());
    }
}
